package com.jackrain.nea.fc.dl.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jackrain.nea.config.PropertiesConf;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.fc.dl.api.ViewReLoadTranOutDataCmd;
import com.jackrain.nea.fc.dl.mapper.WmsBackWriteMapper;
import com.jackrain.nea.sys.CommandAdapter;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.utils.RestTemplateService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * WMS回写
 *
 * @author kangcong
 * @date 2018/08/01
 */
@Slf4j
@Component
@Service(protocol = "dubbo", validation = "true", version = "1.0", group = "dl")
public class ViewReLoadTranOutDataCmdImpl extends CommandAdapter implements ViewReLoadTranOutDataCmd {
    @Autowired
    private RestTemplateService restTemplateService;
    @Autowired
    private PropertiesConf pconf;
    @Override
    public ValueHolder execute(HashMap map) throws NDSException {

        ValueHolder vh = new ValueHolder();
        WmsBackWriteMapper wmsBackWriteMapper = ApplicationContextHandle.getBean(WmsBackWriteMapper.class);
//        List<HashMap> listData = wmsBackWriteMapper.listTranOutData();
//        JSONArray dataArray = listToJsonarray(listData);
        //查询ES
        JSONArray dataArray = new JSONArray();
        int cntSelect = 0;
        int cntSuccess = 0;
        JSONObject where = new JSONObject();
        where.put("table","DL_B_TRAN_OUT");

        JSONArray cp_c_orig_ids = new JSONArray();
        cp_c_orig_ids.add("206581079021");
        cp_c_orig_ids.add("206265940101");
        cp_c_orig_ids.add("206265940102");
        cp_c_orig_ids.add("206265940103");
        cp_c_orig_ids.add("206265940105");
        cp_c_orig_ids.add("206265940104");
        cp_c_orig_ids.add("206265940107");
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        String endTime = sdf.format(date);
        String beginTime = sdf.format(date.getTime()-1000*60*60*24*3);
        String str = "{'WMS_OUT':'[=N]','STATUS':'[=2]','SEND_STATUS':'[=1]','TRAN_FLAG':'[=0]','MODIFIEDDATE':'#{MODIFIEDDATE}','CP_C_ORIG_ID':'#{CP_C_ORIG_ID}'}";
        String solr = str
                .replace("#{MODIFIEDDATE}", beginTime + "~" + endTime)
                .replace("#{CP_C_ORIG_ID}",cp_c_orig_ids.toJSONString());
        where.put("fixedcolumns",solr);
        where.put("startindex",0);
        where.put("isolr",true);
        where.put("range",200);
        String param = where.toJSONString();
        try {
            log.debug("ViewReLoadTranOutDataCmdImpl--param-->{}",param);
//            log.debug("调拨出库补偿查es参数------------->"+param);
            JSONArray array =  esQuery(param);
            if(array != null && array.size() > 0) {
                cntSelect = array.size();
                log.debug("ViewReLoadTranOutDataCmdImpl--array-->{}",array);
//                log.debug("调拨出库补偿查es返回数据------------->" + array);
                for (int i = 0; i < array.size(); i++) {
                    Long ids = array.getLong(i);
                    Long id = wmsBackWriteMapper.selectOutId(ids);
                    if (id > 0) {
                        dataArray.add(ids);
                    }
                }
                cntSuccess = dataArray.size();
            }
        } catch (Exception e) {
            throw new NDSException(e.getMessage(),e);
        }
//        log.debug("查询数据" + cntSelect + "条" + "，发送数据" + cntSuccess + "条，"+dataArray.toString());
        vh.put("data", dataArray);
        vh.put("code", 0);
        vh.put("message", "查询数据" + cntSelect + "条" + "，发送数据" + cntSuccess + "条，"+dataArray.toString());
        return vh;
    }

    public JSONArray esQuery(String param) throws Exception {

        String erpUrl = pconf.getProperty("fc.edas.url", "");
        URI uri = new URI(erpUrl + "/fc/api/esquery");

        MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
        map.add("searchdata", param);
        map.add("username", "superroot");
        try {
            String retStr = restTemplateService.doPostForm(uri, map);
            JSONObject ret = JSON.parseObject(retStr);
            if (ret.get("code") != null && (int) ret.getInteger("code") == 0) {
                if (ret.getInteger("ROWCOUNT") > 0) {
                    String[] ids = StringUtils.split(ret.getString("IDS"), ",");
                    return (JSONArray) JSON.toJSON(ids);
                }
            } else {
                throw new NDSException("Solr查询失败");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new NDSException(e.getMessage(), e);
        }
        return new JSONArray();
    }

//    /**
//     * list TO jsonarra
//     *
//     * @param mapList
//     * @return jsonArray
//     */
//    public JSONArray listToJsonarray(List<HashMap> mapList) {
//        JSONArray jsonArray = new JSONArray();
//        for (int i = 0; i < mapList.size(); i++) {
//            HashMap map = (HashMap) mapList.get(i);
//            JSONObject jsonObject = new JSONObject(map);
//            JSONObject param = JSON.parseObject(JSON.toJSONStringWithDateFormat(jsonObject, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue), Feature.OrderedField);
//            jsonArray.add(param);
//        }
//        return jsonArray;
//    }
}
